/*
 * @Author: liu.lin liu.lin@hzleaper.com
 * @Date: 2023-11-14 11:20:05
 * @LastEditors: liu.lin liu.lin@hzleaper.com
 * @LastEditTime: 2023-11-24 11:15:02
 * @FilePath: \aoi_link_frontend\src\page\fpy-analyse-detail\index.tsx
 * @Description: 这是直通率分析明细页
 */
import { Button, Pagination, Spin, Table } from 'antd';
import { columns } from './table.header';
import { TableType, SearchType } from './index.type';
import { useNavigate, useLocation } from 'react-router-dom';
import { FC, useEffect, useState } from 'react';
import { getQueryDetailFpy, getQueryDetailFpyExport } from '@/api/fpy-analyse-detail/index';
import './index.less';

// 这个页面根据业务来自行设计吧
const FpyAnalyseDetail: FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [tableDatas, setTableDatas] = useState<TableType[]>([]);
  const [isTableLoading, setIsTableLoading] = useState(false);
  const [isExportLoading, setIsExportLoading] = useState(false);
  const [total, setTotal] = useState(0);

  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(8);

  useEffect(() => {
    initData();
  }, []);

  /**
   * @description: 接受路由传递参数
   * @return {*}
   */
  const initData = async () => {
    console.log(`location`, location.state);
    const params: SearchType = location.state;
    const newParams = { pageNum, pageSize, ...params };
    const res = await getQueryDetailFpy(newParams);
    console.log(`res`, res);
    const { total, list } = res.data;
    if (res.code === 200) {
      setTableDatas(list);
      setTotal(total);
    }
  };

  /**
   * @description: 点击分页
   * @param {number} page
   * @return {*}
   */
  const onChangePage = async (page: number) => {
    console.log(`onChangePage`, page);
    try {
      setIsTableLoading(true);
      const newParams = { pageNum, pageSize, ...location.state };
      newParams.pageNum = page;
      console.log(`newParams`, newParams);
      const res = await getQueryDetailFpy(newParams);
      console.log(`res`, res);
      const { total, list } = res.data;
      if (res.code === 200) {
        setTableDatas(list);
        setPageNum(page);
        setTotal(total);
        setIsTableLoading(false);
      }
    } catch (error) {
      console.log(`error`, error);
    }
  };

  /**
   * @description: 返回上一级页面
   * @return {*}
   */
  const handleBack = () => {
    navigate('/layout/fpy-analyse');
  };

  /**
   * @description: 导出excel
   * @return {*}
   */
  const handleExport = async () => {
    console.log(`handleExport`);
    try {
      setIsExportLoading(true);
      const newParams = { ...location.state };
      const res = await getQueryDetailFpyExport(newParams);
      console.log(`res`, res);

      // 处理文件下载
      const blob = new Blob([res], { type: 'application/octet-stream' });
      const downloadLink = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = downloadLink;
      const time = getTime();
      link.download = `${time}_直通率明细.xlsx`;
      link.click();
      setIsExportLoading(false);
    } catch (error) {
      console.log(`error`, error);
    }
  };

  const getTime = () => {
    const date = new Date(); // 创建一个 Date 对象，代表当前时间

    // 获取年、月、日、时、分、秒
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 注意，getMonth() 返回的是 0-11 的值，需要加上 1 才是实际的月份
    const day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();

    // 格式化年、月、日、时、分、秒，确保显示为两位数
    const formattedYear = String(year);
    const formattedMonth = String(month).padStart(2, '0');
    const formattedDay = String(day).padStart(2, '0');
    const formattedHours = String(hours).padStart(2, '0');
    const formattedMinutes = String(minutes).padStart(2, '0');
    const formattedSeconds = String(seconds).padStart(2, '0');

    // 拼接成年月日时分秒字符串
    const dateTimeString = `${formattedYear}-${formattedMonth}-${formattedDay} ${formattedHours}.${formattedMinutes}.${formattedSeconds}`;
    return dateTimeString;
  };

  return (
    <div className="fpy_detail">
      <Spin spinning={isTableLoading}>
        <div className="fpy_detail_header">
          <Button onClick={handleBack}>返回上一级</Button>
          <Button onClick={handleExport} loading={isExportLoading}>
            导出
          </Button>
        </div>
        <div className="fpy_detail_table">
          <Table columns={columns} dataSource={tableDatas} bordered pagination={false} />
        </div>
        <div className="fpy_detail_footer">
          <Pagination current={pageNum} total={total} pageSize={pageSize} showSizeChanger={false} onChange={onChangePage} />
        </div>
      </Spin>
    </div>
  );
};
export default FpyAnalyseDetail;
